package be.vanderveer.services.webthumb;

import java.io.StringReader;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

/**
 * The response recieved from the webthumb API after a request for a thumbnail.
 * 
 * @author Roderik van der Veer
 */
public class WebThumbJobResponse {

	private int estimate;
	private String webthumbid;

	public WebThumbJobResponse(final String xml) {
		super();
		parseResponse(xml);
	}

	private void parseResponse(final String xml) {
		try {
			final SAXBuilder builder = new SAXBuilder();
			final Document doc = builder.build(new StringReader(xml));
			final Element el = doc.getRootElement().getChild("jobs").getChild("job");
			setWebThumbId(el.getTextTrim());
			setEstimate(el.getAttribute("estimate").getIntValue());
		} catch (final Exception e) {
			throw new RuntimeException("Something went wrong, check the stacktrace", e);
		}
	}

	/**
	 * Return the number of seconds to wait before the thumb is ready. As th
	 * ename states, this is an estimate, don't count on it being ready after
	 * this amount. But don't check before.
	 * 
	 * @return the number of seconds to wait before the thumb is ready
	 */
	public int getEstimate() {
		return estimate;
	}

	private void setEstimate(final int estimate) {
		this.estimate = estimate;
	}

	/**
	 * Return the unique identifier for this specific thumbnail.
	 * 
	 * @return the unique identifier for this specific thumbnail
	 */
	public String getWebThumbId() {
		return webthumbid;
	}

	private void setWebThumbId(final String webthumbid) {
		this.webthumbid = webthumbid;
	}

	@Override
	public String toString() {
		return "WebThumbJobResponse: id=" + getWebThumbId() + " - eta=" + getEstimate(); 
	}
	
	
}
